<?php

class AnswerController extends BaseController
{
    protected $tableName = "answer";
    protected $pk = "answer_id";


    // GET
    public function getComments($id)
    {
        $answer = $this->get($id)['data'];
        if (empty($answer)) {
            return ReturnHelper::failed([], "问题id不存在");
        }
        // 判断是否登录，如果已登录还需返回该评论是否是由当前用户发表的信息
        $loginInfo = LoginController::getLoginInfo();
        $sqlPart = "FALSE 'byLoginUser'";
        if ($loginInfo['isLogin']) {
            $user_id = $loginInfo['user_id'];
            $sqlPart = "IF(u.user_id = $user_id, true, false) 'byLoginUser'";
        }
        $sql = "SELECT '用户信息', u.user_id, u.nickname, u.avatar_url, $sqlPart,
                        '评论信息', c.comment_id, c.comment_content, c.create_time
                FROM `comment` c 
                INNER JOIN `user` u 
                    ON c.user_id = u.user_id
                WHERE answer_id = $id
                ORDER BY c.create_time DESC";
//        echo $sql; die();
        $result = $this->conn->query($sql);
        $data = $this->getArrayDataFromResult($result);
        $commentController = new CommentController();
        for ($i = 0; $i < count($data); $i++) {
            $replies = $commentController->getReplies($data[$i]['comment_id']);
            $data[$i]['replies'] = $replies['data'];
        }
        if (empty($data)) {
            return ReturnHelper::failed([], "该问题的评论为空");
        } else {
            return ReturnHelper::success($data, "数据请求成功");
        }
    }

    //POST 新增一个回答
    public function post($obj)
    {
        $user_id = $obj['user_id'];
        $question_id = $obj['question_id'];
        $answer_content = $obj['answer_content'];
        $answer_text = $obj['answer_text'];
        $sql = "INSERT INTO answer VALUES(0, $user_id, $question_id, '$answer_content', '$answer_text', 0, 0, 0, CURRENT_TIME, CURRENT_TIME)";
        $result = $this->conn->query($sql);
        if ($this->judge($this->judge($result))) {
            $newRecord = $this->getNewRecord($obj);
            return ReturnHelper::success($newRecord, "用户`$user_id`新增回答成功");
        }
        else {
            return ReturnHelper::success([], "用户新增回答失败：" . $this->conn->error);
        }
    }

    public function update($id, $obj)
    {
        $user_id = $obj['user_id'];
        $getRes = $this->get($id)['data'];
        if ($getRes['user_id'] != $user_id) {
            return ReturnHelper::failed([], "你不是该回答的作者，无法修改这篇文章");
        }
        return parent::update($id, $obj);
    }
}